const PERMISSIONS_STORAGE_KEY = 'permissions_data'
export default {
  namespaced: true,
  state: () => ({
    roles: [], // 角色列表
    permissions: [], //权限列表
    rolePermissions: {}, // 角色-权限映射
    isInitialized: false,
    lastUpdateTime: null // 添加最后更新时间
  }),
  mutations: {
    /**
     * @description 获取角色列表
     * @param {Object} state
     * @param {Object} roles
     */
    SET_ROLES(state, roles) {
      state.roles = roles
      console.log('角色表', state.roles)
    },
    /**
     * @description 获取权限列表
     * @param {Object} state
     * @param {Object} permissions
     */
    SET_PERMISSIONS(state, permissions) {
      state.permissions = permissions
      console.log('权限表', state.permissions)
    },
    /**
     * @ 设置角色-权限列表
     * @param {object} state 
     * @param {object} roles 
     * @param {object} permissions 
     */
    SET_ROLE_PERMISSIONS(state, {
      roles,
      permissions
    }) {
      // 构建角色-权限映射
      const rolePermissions = {}
      roles.forEach(role => {
        rolePermissions[role.id] = role.permissions.map(p => p.id)
        state.rolePermissions = rolePermissions
      })
      console.log('角色权限表', state.rolePermissions)
    },
    SET_INITIALIZED(state, status) {
      state.isInitialized = status
    },
    // 设置最新的打卡时间
    SET_LAST_UPDATE_TIME(state, time) {
      state.lastUpdateTime = time
    }
  },
  actions: {
    /**
     * @description 初始化权限
     */
    async initPermissions({
      commit,
      state,
      dispatch
    }) {
      if (state.isInitialized) return
      try {
        // 从缓存中加载初始化数据
        const loadedData = await dispatch('loadPermissionFromStorage')
        if(loadedData)  {
          console.log('缓存中加载权限数据成功')
          return
        }
        // 初始化权限
        const {
          data: res
        } = await uni.$http.get('/roles')
        // 设置角色列表
        commit('SET_ROLES', res.data.roles)
        // 设置权限列表
        commit('SET_PERMISSIONS', res.data.permissions)
        // 设置角色-权限映射，这里的话要修改一下，变成用角色名
        commit('SET_ROLE_PERMISSIONS', {
          roles: res.data.roles,
          permissions: res.data.roles.permissions
        })
        // 更新最后更新时间
        const currentTime = Date.now()
        commit('SET_LAST_UPDATE_TIME', currentTime)
        // 标记初始化
        commit('SET_INITIALIZED', true)
        // 保存到本地存储
        await dispatch('savePermissionsToStorage')
      } catch (error) {
        console.log('初始化权限失败:', error)
        uni.$showMsg('获取权限失败')
        throw error
      }
    },
    // 保存权限数据到本地存储
    async savePermissionsToStorage({
      state
    }) {
      try {
        const permissionData = {
          roles: state.roles,
          permissions: state.permissions,
          rolePermissions: state.rolePermissions,
          lastUpdateTime: state.lastUpdateTime
        }
        await uni.setStorage({
          key: PERMISSIONS_STORAGE_KEY,
          data: JSON.stringify(permissionData)
        })
      } catch (error) {
        console.error('保存权限数据失败:', error)
      }
    },
    // 从本地加载权限数据
    async loadPermissionFromStorage({
      commit
    }) {
      try {
        const storage = await uni.getStorage({
          key: PERMISSIONS_STORAGE_KEY
        })
        if (!storage || !storage.data) return false
        const permissionsData = JSON.parse(storage.data)
        // 检查数据是否过期，这里设置24小时过期
        const expirationTime = 24 * 60 * 60 * 1000 // 24小时
        if (Date.now() - permissionsData.lastUpdateTime > expirationTime) {
          await uni.removeStorage({
            key: PERMISSIONS_STORAGE_KEY
          })
          return false
        }
        // 恢复权限数据
        commit('SET_ROLES', permissionsData.roles)
        commit('SET_PERMISSIONS', permissionsData.permissions)
        commit('SET_ROLE_PERMISSIONS', {
          roles: permissionsData.roles,
          permissions: permissionsData.permissions
        })
        commit('SET_LAST_UPDATE_TIME', permissionsData.lastUpdateTime)
        commit('SET_INITIALIZED', true)
        return true
      } catch (error) {
        console.error('加载权限数据失败:', error)
        return false
      }
    },
    // 重置权限状态
    async resetPermissions({
      commit
    }) {
      commit('SET_ROLES', [])
      commit('SET_PERMISSIONS', [])
      commit('SET_ROLE_PERMISSIONS', { roles: [], permissions: [] })
      commit('SET_INITIALIZED', false)
      commit('SET_LAST_UPDATE_TIME', null)
      
      // 消除本地存储
      try {
        await uni.removeStorage({ key: PERMISSIONS_STORAGE_KEY })
      }catch(error) {
        console.error('消除权限数据失败:',error)
      }
    }

  },
  getters: {
    // 获取所有角色
    roles: state => state.roles,

    // 获取所有权限
    permissions: state => state.permissions,

    // 获取角色-权限映射
    rolePermissions: state => state.rolePermissions,

    // 检查是否有特定权限
    hasPermission: (state) => (permissionId) => {
      return state.permissions.some(p => p.id === permissionId)
    },

    // 检查角色是否有特定的权限,等会会用到这个
    hasRolePermission: (state) => (roleId, permissionId) => {
      return state.rolePermissions[roleId]?.includes(permissionId) || false
    },
    // 获取角色所有的权限,这个等会也会用到
    getRolePermissions: (state) => (roleId) => {
      return state.rolePermissions[roleId] || []
    },
    // 检查是否有多个权限中的任意一个
    hasAnyPermission: (state) => (permissionIds) => {
      return permissionIds?.some(id =>
        state.permissions?.some(p => p.id === id)
      )
    },
    // 检查是否有多个角色中的任意一个
    hasAnyRole: (state) => (roleIds) => {
      return roleIds.some(id =>
        state.roles.some(r => r.id === id)
      )
    },
    // 检查是否有特定角色
    hasRole: (state) => (roleId) => {
      return state.roles.some(r => r.id === roleId)
    },
  }
}